// Copyright 2015 Quuppa Oy. All rights reserved.
var Q = Q || {};
var ctx = null;
var points=[];
var canvas = null;
Q.Map2DInteractionManager = function(map, selectionManager) {
	// this.map = map;
	map = map;
	// isLeftMouseButtonDown = false;
	leftMouseDownPos = undefined; // [0, 0];
	touchStartPos = undefined;

	this.disablePan = false;
	that = this;
	canvas = document.getElementById("mapCanvas");
	ctx = canvas.getContext('2d');

	this.onMouseDown = function(event) {
		event.preventDefault();
		if (event.button === 1) {
			leftMouseDownPos = [ event.clientX, event.clientY ];
		}
	};

	this.onMouseMove = function(event) {
		event.preventDefault();
		if (event.button === 0 &&/* isLeftMouseButtonDown  leftMouseDownPos !== undefined */leftMouseDownPos !== undefined) {
			var dx = event.clientX - leftMouseDownPos[0];
			var dy = event.clientY - leftMouseDownPos[1];
			map.viewport.pan(-dx, -dy);
			map.render();
			leftMouseDownPos[0] = event.clientX;
			leftMouseDownPos[1] = event.clientY;
		}

		var drawables = map.getDrawables();
		var hitObjects = [];
		for(var i = drawables.length - 1; i >= 0 ; i--) {
			if(drawables[i].setHighlighted !== undefined)  // reset all highlights
				drawables[i].setHighlighted(false);

			if(drawables[i].hitTest !== undefined) {
				var isHit = drawables[i].hitTest(event.offsetX, event.offsetY, map.viewport);
				if(isHit) {
					hitObjects.push(drawables[i]);
				}
			}
		}
		if(hitObjects.length > 0) {
			var msg = "";
//			for(var i = 0; i < hitObjects.length; i++) {
			if(hitObjects[0].setHighlighted !== undefined)
				hitObjects[0].setHighlighted(true);
			if(hitObjects[0].name && hitObjects[0].name.length > 0) {
				msg += hitObjects[0].name + " ";
			}
//			}
// 			map.renderLabel(msg, [event.offsetX, event.offsetY]);
		} else {
			// map.renderLabel(undefined, undefined);  // clear label
		}
		// map.render();
//		var screen = [event.offsetX, event.offsetY];
//		var metres = map.viewport.transformToCoordsM(screen);
//		var s = metres[0] + ":" + metres[1];
//		map.renderLabel(s, screen);
		var px = [event.offsetX, event.offsetY];
		//console.log(px + "(px) => " + map.viewport.transformToCoordsM(px) + "(m)");
	};

	this.onMouseUp = function(event) {
		event.preventDefault();
		if (event.button === 1 /* && isLeftMouseButtonDown */) {
			// isLeftMouseButtonDown = false;
			leftMouseDownPos = undefined;
		}
	};

	this.onMouseWheel = function(event, delta) {
		ctx.clearRect(0,0,canvas.width,canvas.height);
		points=[];
		if (delta > 0) {
			var e = event.originalEvent;
			zoomIn([ e.offsetX || e.layerX, e.offsetY || e.layerY ]);
			//console.log(event.originalEvent.layerX +":"+ event.originalEvent.layerX);
		} else {
			zoomOut();
		}
	};
	this.onTouchStart = function(event) {
		event.preventDefault();
		// act only if there's exactly one finger inside this element
		if (event.targetTouches.length == 1) {
			var touch = event.targetTouches[0];
			touchStartPos = [ touch.clientX, touch.clientY ];
			console.log("start at " + touchStartPos[0] +":"+ touchStartPos[1]);
		}
	};
	this.onTouchMove = function(event) {
		event.preventDefault();
		// act only if there's exactly one finger inside this element
		if (event.targetTouches.length == 1 && touchStartPos !== undefined) {
			var touch = event.targetTouches[0];
			var dx = touch.clientX - touchStartPos[0];
			var dy = touch.clientY - touchStartPos[1];
			map.viewport.pan(-dx, -dy);
			map.render();
			touchStartPos[0] = touch.clientX;
			touchStartPos[1] = touch.clientY;
		}
	};
	this.onTouchEnd = function(event) {
		event.preventDefault();
		// act only if there's exactly one finger inside this element
		if (event.targetTouches.length == 1) {
			touchStartPos = undefined;
		}
	};

	this.onClick = function(event) {
		event.preventDefault();
		// act only if there's exactly one finger inside this element
		var drawables = map.getDrawables();
		var metres = map.viewport.transformToCoordsM([event.offsetX, event.offsetY]);
		console.log(metres[0], metres[1]);//转换后的坐标

		// //鼠标点击生成一个小方块
		// ctx.fillStyle = 'red'; // 设置填充颜色
		// ctx.strokeStyle = 'red'; // 设置描边颜色
		// ctx.beginPath()
		// if (points.length<2){
		// 	ctx.arc(event.offsetX,event.offsetY,5,0,2*Math.PI);
		// }
		// if (1 == 1)
		// 	ctx.fill()
		// else
		// 	ctx.stroke()
		// ctx.closePath()
		// points.push({
		// 	x: event.offsetX,
		// 	y: event.offsetY
		// });
		// console.log(points);
		// if (points.length==2){
		// 	//两点绘制一个矩形
		// 	//鼠标点击生成一个小方块
		// 	ctx.fillStyle = 'blue'; // 设置填充颜色
		// 	ctx.strokeStyle = 'red'; // 设置描边颜色
		// 	ctx.beginPath()
		// 	ctx.rect(points[0].x,points[0].y,points[1].x-points[0].x,points[1].y-points[0].y);
		// 	if (1 == 1)
		// 		ctx.fill()
		// 	else
		// 		ctx.stroke()
		// 	ctx.closePath();

		// }

	};

	zoomOut = this.zoomOut = function() {
		map.viewport.scale = map.viewport.scale * 0.8;
		if(map.viewport.scale < 1)
			map.viewport.scale = 1;
		map.render();
	};
	clearRectMap = this.clearRectMap = function() {
		map.render();
	};
	selectOperation = this.selectOperation = function(type) {
		var cvs = document.getElementById("mapCanvas");
		var cxt=cvs.getContext("2d");
		DrawingManager.setCanvas("mapCanvas");
		//事件
		var mousemanager = document.getElementById("mapCanvas");
		mousemanager.addEventListener("mousedown",mousedownhandler);
		mousemanager.addEventListener("mouseup",mouseuphandler);
		mousemanager.addEventListener("dblclick",mousedbhandler);
		DrawingManager.shapetype = type;//绘制多边形
		function mousedownhandler(e){
			//    DrawingManager.drawFirstRectPoint(e.clientX,e.clientY);
			switch(DrawingManager.shapetype){
				case 1:
					$("#drawWay").val("1");//矩形
					DrawingManager.drawFirstRectPoint(e.clientX,e.clientY);
					break;
				case 2:
					$("#drawWay").val("2");//多边形
					DrawingManager.drawTempshape(2,e.clientX,e.clientY);
					break;
				case 3:
					$("#drawWay").val("3");//线段
					DrawingManager.drawTempshape(3,e.clientX,e.clientY);
					break;
				case 4:
					break;
			}
		}
	};
	zoomIn = this.zoomIn = function(mousePos) {
		map.viewport.scale = map.viewport.scale * 1.2;
		if(map.viewport.scale > 100)
			map.viewport.scale = 100;
		if (mousePos !== undefined && mousePos instanceof Array
			&& mousePos.length === 2) {
			// compute how much we need to pan so that map zooms to mouse
			// pointer
			var x = mousePos[0] - map.viewport.w / 2;
			var y = mousePos[1] - map.viewport.h / 2;
			map.viewport.pan(x * 0.1, y * 0.1);
		}
		map.render();
	};

	rotateCW = this.rotateCW = function() {
		map.viewport.rotation += 90.0;
		map.render();
	};

	rotateCCW = this.rotateCCW = function() {
		map.viewport.rotation -= 90.0;
		map.render();
	};

	/**
	 *
	 */
	var DrawingManager;//创建命名空间
	if(!DrawingManager) DrawingManager = {};
	DrawingManager.mode = {//默认模式
		strokeColor : "red",
		fillColor : "#0000ff",
		strokeWidth : 2,        //边框宽度，固定
		strokeOpacity : 0.8,    //边框透明度，固定
		fillOpacity : 0.5,      //填充透明度，固定
		strokeStyle : "solid",  //边框样式，固定
	};
//指定画布
	DrawingManager.setCanvas = function(element){
		e = document.getElementById("mapCanvas");
		DrawingManager.cvs_ctx = e.getContext("2d");
		DrawingManager.cvs_Bounding = e.getBoundingClientRect();
	};
//轮廓样式
	DrawingManager.useStrokeCss = function(color){
		if(!DrawingManager.cvs_ctx){
			alert("未指定画布");
			return
		}
		var ctx = DrawingManager.cvs_ctx;
		ctx.globalAlpha = this.mode.strokeOpacity;
		ctx.strokeStyle = color || this.mode.strokeColor;
	};

//图形填充样式
	DrawingManager.useFillCss = function(color){
		if(!DrawingManager.cvs_ctx){
			alert("未指定画布");
			return
		}
		var ctx = DrawingManager.cvs_ctx;
		ctx.lineWidth = this.mode.strokeWidth;
		ctx.fillStyle = color||this.mode.fillColor;
		ctx.globalAlpha = this.mode.fillOpacity;
	};
//绘制矩形
	DrawingManager.drawrect = function(x,y,w,h,color){
		if(!DrawingManager.cvs_ctx){
			alert("未指定画布");
			return
		}
		var ctx = DrawingManager.cvs_ctx;
		this.useFillCss();
		ctx.fillRect(x,y,w,h);
		this.useStrokeCss();
		ctx.strokeRect(x,y,w,h);
	};
//绘制提示点
	DrawingManager.drawtip = function(x,y,color){
		if(!DrawingManager.cvs_ctx){
			alert("未指定画布");
			return
		}
		var ctx = DrawingManager.cvs_ctx;
		var ctx_b = DrawingManager.cvs_Bounding;

		var tip_w = 5;
		var tip_h = 5;
		var startpoint = {};
		startpoint.x = x - tip_w/2;
		startpoint.y = y - tip_h/2;
		if(startpoint.x < 0)
			startpoint.x = 0;
		if(startpoint.y < 0)
			startpoint.y = 0;

		var stoppoint = {};
		stoppoint.x = x + tip_w/2;
		stoppoint.y = y + tip_h/2;
		if(stoppoint.x > ctx_b.width)
			stoppoint.x = ctx_b.width;
		if(stoppoint.y > ctx_b.height)
			stoppoint.y = ctx_b.height;
		ctx.lineWidth = 2;
		ctx.fillStyle = color||this.mode.fillColor;
		ctx.globalAlpha = 1;
		ctx.strokeStyle = color || this.mode.strokeColor;
		ctx.strokeRect(startpoint.x,startpoint.y,stoppoint.x-startpoint.x,stoppoint.y-startpoint.y);
		//矩形四个点坐标保存
		//坐标转换
		var g_point= DrawingManager.g_point;
		if (g_point.length==2){
			if (g_point[1]!=null){
				var point1 = map.viewport.transformToCoordsM([g_point[0].x,g_point[0].y]);
				var point2 = map.viewport.transformToCoordsM([g_point[0].x,g_point[1].y]);
				var point3 = map.viewport.transformToCoordsM([g_point[1].x,g_point[1].y]);
				var point4 = map.viewport.transformToCoordsM([g_point[1].x,g_point[0].y]);
				var pointData =point1+"|"+point2+"|"+point3+"|"+point4+"|"+point1;
				$("#pointData").val(pointData);
			}
		}

	};

	DrawingManager.g_point = new Array(2);

	DrawingManager.drawFirstRectPoint = function(x,y){
		if(DrawingManager.shapetype != 1)
			return;
		if(!DrawingManager.cvs_ctx){
			alert("未指定画布");
			return
		}
		var ctx_b = DrawingManager.cvs_Bounding;

		var point = DrawingManager.g_point;
		var drawx = x - ctx_b.left;//相对流量器的坐标
		var drawy = y - ctx_b.top;
		point[0] = {x:drawx,y:drawy};
		DrawingManager.drawtip(point[0].x,point[0].y,"blue");//相对画布的坐标
	};
	DrawingManager.drawLastRectPoint = function(x,y) {
		if(DrawingManager.shapetype != 1)
			return;
		if(!DrawingManager.cvs_ctx){
			alert("未指定画布");
			return
		}
		var ctx_b = DrawingManager.cvs_Bounding;

		var point = DrawingManager.g_point;
		var drawx = x - ctx_b.left;
		var drawy = y - ctx_b.top;
		point[1] = {x:drawx,y:drawy};
		var w = Math.abs(drawx-point[0].x);
		var h = Math.abs(drawy-point[0].y);
		DrawingManager.drawtip(point[1].x,point[1].y,"blue");
		DrawingManager.drawrect(point[0].x<point[1].x?point[0].x:point[1].x,
			point[0].y<point[1].y?point[0].y:point[1].y,w,h,"red");
		selectOperation(4);
	};

	DrawingManager.regin = [];
//绘制多边形
	DrawingManager.drawPolygonAddpoint = function(x,y){
		var ctx_b = DrawingManager.cvs_Bounding;
		var drawx = x - ctx_b.left;
		var drawy = y - ctx_b.top;
		var point = {x:x,y:y};
		this.drawTempshape(2,point);
	};

//展示图形

//临时展示图形
//输入，客户端坐标
	DrawingManager.shapetype = 0;
	DrawingManager.drawTempshape = function(shapetype,x,y){
		var ctx = DrawingManager.cvs_ctx;
		var ctx_b = DrawingManager.cvs_Bounding;
		var ob_data = this.regin;
		//坐标转换成画布坐标
		var newpoint = {};
		newpoint.x = x - ctx_b.left;
		newpoint.y = y - ctx_b.top;
		this.drawtip(newpoint.x,newpoint.y,"blue");
		this.useStrokeCss();
		shapetype = DrawingManager.shapetype;
		switch (shapetype) {
			case 1://矩形
				if(ob_data.length == 1){
					ob_data[1] = newpoint;
					var w = Math.abs(ob_data[1].x-ob_data[0].x);
					var h = Math.abs(ob_data[1].y-ob_data[0].y);
					DrawingManager.drawrect(ob_data[0].x<ob_data[1].x?ob_data[0].x:ob_data[1].x,
						ob_data[0].y<ob_data[1].y?ob_data[0].y:ob_data[1].y,w,h,"red");
				}//加点
				break;
			case 2://多边形
				ob_data[ob_data.length] = newpoint;
				if(ob_data.length == 1){//绘制第一个点
					ctx.beginPath();
					ctx.moveTo(ob_data[0].x, ob_data[0].y);
				}
				if(ob_data.length > 1) {
					ctx.lineTo(ob_data[ob_data.length - 1].x, ob_data[ob_data.length - 1].y);
					ctx.stroke();
				}
				break;
			case 3://折线
				ob_data[ob_data.length] = newpoint;
				//去重
				var datas=[];
				for(var i = 0; i < ob_data.length; i++){
					if(i == 0) datas.push(ob_data[i]);
					b = false;
					if(datas.length > 0 && i > 0){
						for(var j = 0; j < datas.length; j++){
							if(datas[j].x == ob_data[i].x&&datas[j].y == ob_data[i].y){
								b = true;
							}
						}
						if(!b){ datas.push(ob_data[i]);}
					}
				}
				if(datas.length == 1){//绘制第一个点
					ctx.beginPath();
					ctx.moveTo(datas[0].x, datas[0].y);
				}
				if(datas.length == 2) {
					ctx.lineTo(datas[datas.length - 1].x, datas[datas.length - 1].y);
					ctx.stroke();
					//坐标转换
					var point1 = map.viewport.transformToCoordsM([datas[0].x,datas[0].y]);
					var point2 = map.viewport.transformToCoordsM([datas[1].x,datas[1].y]);
					var pointData = point1+"|"+point2+"|"+point1;
					$("#pointData").val(pointData);
					ob_data.length=0;
					ob_data = [];
					selectOperation(4);
				}
				break;
		}
	};
	DrawingManager.drawPolygondone = function(){
		if((this.shapetype != 2 )|| (this.regin.length < 3))
			return;
		if(!DrawingManager.cvs_ctx){
			alert("未指定画布");
			return
		}
		var ctx = DrawingManager.cvs_ctx;
		var ctx_b = DrawingManager.cvs_Bounding;

		var lastpoint = this.regin[this.regin.length-1];
		var firstpoint = this.regin[0];
		ctx.moveTo(lastpoint.x,lastpoint.y);
		ctx.lineTo(firstpoint.x,firstpoint.y);
		ctx.closePath();
		this.useStrokeCss();
		this.useFillCss();
		ctx.stroke();
		ctx.fill();
		var datas=[];
		for(var i = 0; i < this.regin.length; i++){
			if(i == 0) datas.push(this.regin[i]);
			b = false;
			if(datas.length > 0 && i > 0){
				for(var j = 0; j < datas.length; j++){
					if(datas[j].x == this.regin[i].x&&datas[j].y == this.regin[i].y){
						b = true;
					}
				}
				if(!b){ datas.push(this.regin[i]);}
			}
		}
		var pointData = "";
		var point0 = null;
		for (var i = 0;i<datas.length;i++){
			var point = map.viewport.transformToCoordsM([datas[i].x,datas[i].y]);
			if (i==0){
				point0 = map.viewport.transformToCoordsM([datas[i].x,datas[i].y]);
			}
			if (i==datas.length-1){
				pointData =pointData+point+"|"+point0;
			} else {
				pointData =pointData+ point+"|";
			}
		}
		$("#pointData").val(pointData);
		this.regin.length = 0;
		this.regin = [];
		selectOperation(4);
	};
	function mouseuphandler(e){
		DrawingManager.drawLastRectPoint(e.clientX,e.clientY);
	}
	function mousedbhandler(e){//双击事件
		DrawingManager.drawPolygondone();
	}

};



// function selectOperation(type) {
// 	var cvs = document.getElementById("mapCanvas");
// 	var cxt=cvs.getContext("2d");
// 	DrawingManager.setCanvas("mapCanvas");
// 	//事件
// 	var mousemanager = document.getElementById("mapCanvas");
// 	mousemanager.addEventListener("mousedown",mousedownhandler);
// 	mousemanager.addEventListener("mouseup",mouseuphandler);
// 	mousemanager.addEventListener("dblclick",mousedbhandler);
// 	DrawingManager.shapetype = type;//绘制多边形
// 	function mousedownhandler(e){
// 		//    DrawingManager.drawFirstRectPoint(e.clientX,e.clientY);
// 		switch(DrawingManager.shapetype){
// 			case 1:
// 				DrawingManager.drawFirstRectPoint(e.clientX,e.clientY);
// 				break;
// 			case 2:
// 				DrawingManager.drawTempshape(2,e.clientX,e.clientY);
// 				break;
// 			case 3:
// 				break;
// 			case 4:
// 				break;
// 		}
// 	}
// }


